package com.reader.cms.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.reader.cms.config.UploadConfig;
import com.reader.core.entity.ResultMessageInfo;
import com.reader.core.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 
 * @author jiahaikun
 * @阿里云存储上传图片
 */
public class AliOSSUtils {

    private final static Logger logger = LoggerFactory.getLogger(AliOSSUtils.class);
    public AliOSSUtils() {
    	
    }

    /**
     * 图片上传(阿里云)
     * @param file
     * @return
     * @throws Exception
     */
    public static String uploadImg2Oss(MultipartFile file) throws Exception {
        if (file.getSize() > UploadConfig.upload_pictureMaxsize*1024*1024) {//M转换成bytes

             throw new CustomException("上传图片大小不得超过"+UploadConfig.upload_pictureMaxsize+"M!");
         }
    	 
    	String fileHost         =UploadConfig.aliyun_fileHost;
        String originalFilename = file.getOriginalFilename();
        String substring        = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        String name = UUID.randomUUID() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            uploadFile2OSS(inputStream, name);
            return fileHost+"/"+name;
        } catch (Exception e) {
            throw new Exception("upload picture to aliyun  oss failed");
        }

    }

    /**
     * 视频文件上传(阿里云)
     * @param file
     * @return
     * @throws Exception
     */
    public static String uploadVideo2Oss(MultipartFile file) throws Exception {
        if (file.getSize() > UploadConfig.upload_pictureMaxsize*1024*1024) {//M转换成bytes
            throw new CustomException("Upload video size should not exceed "+UploadConfig.upload_pictureMaxsize+"M!");
        }

        String fileHost         =UploadConfig.aliyun_fileHost;
        String originalFilename = file.getOriginalFilename();
        String substring        = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        String name = UUID.randomUUID() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            uploadFile2OSS(inputStream, name);
            return fileHost+"/"+name;
        } catch (Exception e) {
            throw new Exception("upload picture to aliyun  oss failed");
        }

    }
    
    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param instream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public static String uploadFile2OSS(InputStream instream, String fileName) {
    	
    	String endpoint        =UploadConfig.aliyun_endpoint;
    	String accessKeyId     =UploadConfig.aliyun_accessKeyId;
    	String accessKeySecret =UploadConfig.aliyun_accessKeySecret;
    	String bucketName      =UploadConfig.aliyun_bucketName;
    	
    	OSS  ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, fileName, instream, objectMetadata);
            ret = putResult.getETag();

        } catch (IOException e) {
        	logger.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            ossClient.shutdown();
        }
        return ret;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".gif") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/png";
        }
        return "image/jpeg";
    }
    
    
}
